<template>
  <view class="container">
    <view class="page-header">
      <view class="back-btn" @click="goBack">
        <text class="back-icon">&lt;</text>
        <text class="back-text">返回</text>
      </view>
      <view class="page-title">企业员工信息</view>
    </view>
    
    <!-- 无企业员工信息时的提示 -->
    <view class="empty-tip" v-if="!hasProfile && !isEditing">
      <image class="empty-icon" src="/static/images/empty-data.png"></image>
      <text class="empty-text">您尚未设置企业员工信息</text>
      <button class="btn-create" @click="startEdit">立即添加</button>
    </view>
    
    <!-- 员工信息展示区域 -->
    <view class="profile-card" v-if="hasProfile && !isEditing">
      <view class="card-row">
        <text class="card-label">姓名</text>
        <text class="card-value">{{employeeData.name || '未设置'}}</text>
      </view>
      
      <view class="card-row">
        <text class="card-label">性别</text>
        <text class="card-value">{{employeeData.gender === 'M' ? '男' : (employeeData.gender === 'F' ? '女' : '未设置')}}</text>
      </view>
      
      <view class="card-row">
        <text class="card-label">身份证号</text>
        <text class="card-value">{{employeeData.id_card || '未设置'}}</text>
      </view>
      
      <view class="card-row">
        <text class="card-label">所属企业</text>
        <text class="card-value">{{employeeData.company_name || '未设置'}}</text>
      </view>
      
      <view class="card-row">
        <text class="card-label">工号</text>
        <text class="card-value">{{employeeData.employee_no || '未设置'}}</text>
      </view>
      
      <view class="card-row">
        <text class="card-label">部门</text>
        <text class="card-value">{{employeeData.department || '未设置'}}</text>
      </view>
      
      <view class="card-row">
        <text class="card-label">职位</text>
        <text class="card-value">{{employeeData.position || '未设置'}}</text>
      </view>
      
      <view class="card-row">
        <text class="card-label">身份</text>
        <text class="card-value">
          <text v-if="employeeData.is_legal_representative">法人代表</text>
          <text v-else-if="employeeData.is_department_manager">部门经理</text>
          <text v-else>普通员工</text>
        </text>
      </view>
      
      <button class="btn-edit" @click="startEdit">编辑信息</button>
    </view>
    
    <!-- 员工信息编辑区域 -->
    <view class="edit-form" v-if="isEditing">
      <view class="form-group">
        <text class="form-label">所属企业</text>
        <picker class="form-picker" @change="bindCompanyChange" :value="companyIndex" :range="companyList" range-key="company_name">
          <view class="picker-value">
            {{selectedCompany ? selectedCompany.company_name : '请选择企业'}}
          </view>
        </picker>
      </view>
      
      <view class="form-group">
        <text class="form-label">姓名</text>
        <input class="form-input" type="text" v-model="formData.name" placeholder="请输入姓名" />
      </view>
      
      <view class="form-group">
        <text class="form-label">性别</text>
        <picker class="form-picker" @change="bindGenderChange" :value="genderIndex" :range="genders">
          <view class="picker-value">
            {{genders[genderIndex] || '请选择性别'}}
          </view>
        </picker>
      </view>
      
      <view class="form-group">
        <text class="form-label">身份证号</text>
        <input class="form-input" type="idcard" v-model="formData.id_card" placeholder="请输入身份证号" />
      </view>
      
      <view class="form-group">
        <text class="form-label">工号</text>
        <input class="form-input" type="text" v-model="formData.employee_no" placeholder="请输入企业工号" />
      </view>
      
      <view class="form-group">
        <text class="form-label">部门</text>
        <input class="form-input" type="text" v-model="formData.department" placeholder="请输入部门" />
      </view>
      
      <view class="form-group">
        <text class="form-label">职位</text>
        <input class="form-input" type="text" v-model="formData.position" placeholder="请输入职位" />
      </view>
      
      <view class="form-group checkbox-group">
        <label class="checkbox-label">
          <checkbox :checked="formData.is_legal_representative" @tap="toggleLegalRepresentative" />
          <text>法人代表</text>
        </label>
        
        <label class="checkbox-label">
          <checkbox :checked="formData.is_department_manager" @tap="toggleDepartmentManager" />
          <text>部门经理</text>
        </label>
      </view>
      
      <view class="btn-group">
        <button class="btn-cancel" @click="cancelEdit">取消</button>
        <button class="btn-save" @click="saveEmployeeProfile">保存</button>
      </view>
    </view>
  </view>
</template>

<script>
import { getEmployeeProfile, updateEmployeeProfile, getCompanyList } from '@/api/auth.js'

export default {
  data() {
    return {
      hasProfile: false,
      isEditing: false,
      employeeData: {},
      formData: {
        company_id: '',
        name: '',
        gender: '',
        id_card: '',
        employee_no: '',
        department: '',
        position: '',
        is_legal_representative: false,
        is_department_manager: false
      },
      companyList: [],
      companyIndex: 0,
      genders: ['男', '女'],
      genderIndex: 0,
      selectedCompany: null,
      baseUrl: ''  // 基础URL
    }
  },
  
  onLoad() {
    // 获取当前环境下的baseUrl
    this.baseUrl = getApp().globalData.baseUrl || ''
    this.fetchEmployeeProfile()
    this.fetchCompanyList()
  },
  
  methods: {
    // 返回上一页
    goBack() {
      uni.navigateBack()
    },
    
    // 获取企业员工信息
    async fetchEmployeeProfile() {
      try {
        uni.showLoading({ title: '加载中...' })
        
        const res = await getEmployeeProfile()
        console.log('企业员工信息响应:', res)
        
        if (res.code === 200 && res.data) {
          this.employeeData = res.data
          this.hasProfile = true
          
          // 初始化表单数据
          this.formData = {
            company_id: this.employeeData.company_id,
            name: this.employeeData.name || '',
            gender: this.employeeData.gender || 'M',
            id_card: this.employeeData.id_card || '',
            employee_no: this.employeeData.employee_no || '',
            department: this.employeeData.department || '',
            position: this.employeeData.position || '',
            is_legal_representative: this.employeeData.is_legal_representative || false,
            is_department_manager: this.employeeData.is_department_manager || false
          }
          
          // 设置性别索引
          this.genderIndex = this.formData.gender === 'M' ? 0 : 1
          
        } else if (res.code === 404) {
          this.hasProfile = false
        } else {
          uni.showToast({
            title: res.message || '获取企业员工信息失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('获取企业员工信息失败:', error)
        uni.showToast({
          title: '网络错误，请稍后再试',
          icon: 'none'
        })
      } finally {
        uni.hideLoading()
      }
    },
    
    // 获取企业列表
    async fetchCompanyList() {
      try {
        const res = await getCompanyList()
        
        if (res.code === 200 && res.data && res.data.list) {
          this.companyList = res.data.list
          
          // 如果已有企业员工信息，设置对应的企业索引
          if (this.hasProfile && this.employeeData.company_id) {
            const index = this.companyList.findIndex(company => 
              company.company_id === this.employeeData.company_id
            )
            
            if (index !== -1) {
              this.companyIndex = index
              this.selectedCompany = this.companyList[index]
            }
          }
        }
      } catch (error) {
        console.error('获取企业列表失败:', error)
      }
    },
    
    // 开始编辑
    startEdit() {
      this.isEditing = true
      
      // 如果没有企业员工信息，初始化表单数据
      if (!this.hasProfile) {
        this.formData = {
          company_id: this.companyList.length > 0 ? this.companyList[0].company_id : '',
          name: '',
          gender: 'M',
          id_card: '',
          employee_no: '',
          department: '',
          position: '',
          is_legal_representative: false,
          is_department_manager: false
        }
        
        if (this.companyList.length > 0) {
          this.selectedCompany = this.companyList[0]
        }
      }
    },
    
    // 取消编辑
    cancelEdit() {
      if (this.hasProfile) {
        // 重置表单数据
        this.formData = {
          company_id: this.employeeData.company_id,
          name: this.employeeData.name || '',
          gender: this.employeeData.gender || 'M',
          id_card: this.employeeData.id_card || '',
          employee_no: this.employeeData.employee_no || '',
          department: this.employeeData.department || '',
          position: this.employeeData.position || '',
          is_legal_representative: this.employeeData.is_legal_representative || false,
          is_department_manager: this.employeeData.is_department_manager || false
        }
      }
      
      this.isEditing = false
    },
    
    // 保存企业员工信息
    async saveEmployeeProfile() {
      // 验证必填项
      if (!this.formData.company_id) {
        uni.showToast({
          title: '请选择所属企业',
          icon: 'none'
        })
        return
      }
      
      if (!this.formData.name) {
        uni.showToast({
          title: '请输入姓名',
          icon: 'none'
        })
        return
      }
      
      try {
        uni.showLoading({ title: '保存中...' })
        
        // 将性别转换为 M/F 格式
        this.formData.gender = this.genderIndex === 0 ? 'M' : 'F'
        
        const res = await updateEmployeeProfile(this.formData)
        
        if (res.code === 200) {
          uni.showToast({
            title: res.message || '保存成功',
            icon: 'success'
          })
          
          // 重新获取员工信息
          this.fetchEmployeeProfile()
          this.isEditing = false
        } else {
          uni.showToast({
            title: res.message || '保存失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('保存企业员工信息失败:', error)
        uni.showToast({
          title: '网络错误，请稍后再试',
          icon: 'none'
        })
      } finally {
        uni.hideLoading()
      }
    },
    
    // 企业选择器变化
    bindCompanyChange(e) {
      const index = e.detail.value
      this.companyIndex = index
      this.selectedCompany = this.companyList[index]
      this.formData.company_id = this.selectedCompany.company_id
    },
    
    // 性别选择器变化
    bindGenderChange(e) {
      this.genderIndex = e.detail.value
    },
    
    // 切换法人代表状态
    toggleLegalRepresentative() {
      this.formData.is_legal_representative = !this.formData.is_legal_representative
    },
    
    // 切换部门经理状态
    toggleDepartmentManager() {
      this.formData.is_department_manager = !this.formData.is_department_manager
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  padding: 30rpx;
  background-color: #f8f8f8;
  min-height: 100vh;
}

.page-header {
  display: flex;
  align-items: center;
  margin-bottom: 40rpx;
  position: relative;
}

.back-btn {
  display: flex;
  align-items: center;
  position: absolute;
  left: 0;
}

.back-icon {
  font-size: 36rpx;
  color: #007AFF;
}

.back-text {
  font-size: 28rpx;
  color: #007AFF;
}

.page-title {
  font-size: 36rpx;
  font-weight: bold;
  flex: 1;
  text-align: center;
}

.empty-tip {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
}

.empty-icon {
  width: 200rpx;
  height: 200rpx;
  margin-bottom: 30rpx;
}

.empty-text {
  font-size: 32rpx;
  color: #999;
  margin-bottom: 40rpx;
}

.btn-create {
  background-color: #007AFF;
  color: #ffffff;
  font-size: 32rpx;
  border-radius: 45rpx;
  width: 300rpx;
  height: 80rpx;
  line-height: 80rpx;
}

.profile-card {
  background-color: #ffffff;
  border-radius: 12rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
}

.card-row {
  display: flex;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}

.card-label {
  width: 200rpx;
  font-size: 28rpx;
  color: #666;
}

.card-value {
  flex: 1;
  font-size: 28rpx;
  color: #333;
}

.btn-edit {
  margin-top: 40rpx;
  background-color: #007AFF;
  color: #ffffff;
  font-size: 32rpx;
  border-radius: 45rpx;
  height: 80rpx;
  line-height: 80rpx;
}

.edit-form {
  background-color: #ffffff;
  border-radius: 12rpx;
  padding: 30rpx;
}

.form-group {
  margin-bottom: 30rpx;
}

.form-label {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 10rpx;
  display: block;
}

.form-input, .form-picker {
  width: 100%;
  height: 80rpx;
  border: 1rpx solid #e0e0e0;
  border-radius: 8rpx;
  padding: 0 20rpx;
  font-size: 28rpx;
  background-color: #f8f8f8;
}

.picker-value {
  height: 80rpx;
  line-height: 80rpx;
}

.checkbox-group {
  display: flex;
  flex-direction: row;
  align-items: center;
}

.checkbox-label {
  display: flex;
  align-items: center;
  margin-right: 40rpx;
  font-size: 28rpx;
}

.btn-group {
  display: flex;
  margin-top: 40rpx;
}

.btn-cancel {
  flex: 1;
  background-color: #f5f5f5;
  color: #666;
  font-size: 32rpx;
  border-radius: 45rpx;
  height: 80rpx;
  line-height: 80rpx;
  margin-right: 20rpx;
}

.btn-save {
  flex: 1;
  background-color: #007AFF;
  color: #ffffff;
  font-size: 32rpx;
  border-radius: 45rpx;
  height: 80rpx;
  line-height: 80rpx;
}
</style> 